package common.server.utils;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;


/**
 * java对象与xml字符串相互转换
 */
public class XmlUtils {

	/**xml转换为java对象*/
	public static Object xmlToBean(String xmlStr, Class<?> load) {

		Object object = null;
		try {
			
			JAXBContext context = JAXBContext.newInstance(load);
			
			Unmarshaller unmarshaller = context.createUnmarshaller();
			
			StringReader sr = new StringReader(xmlStr);
			
			object = unmarshaller.unmarshal(sr);
		} catch (JAXBException e) {
			e.printStackTrace();
		}
		
		return object;
	}
	
	/**java对象转换为xml字符串*/
	public static String beanToXml(Object obj,Class<?> load){
		
		StringWriter writer = null;
		try {
			
			JAXBContext context = JAXBContext.newInstance(load);
			Marshaller marshaller = context.createMarshaller();
			
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
			
			writer = new StringWriter();
			marshaller.marshal(obj,writer);
		} catch (JAXBException e) {
			e.printStackTrace();
		}
	       
		return writer.toString().replace("standalone=\"yes\"", "");
	}
	
	public static void main(String[] args) throws JAXBException {
		

	}
}
